package top.igotcha.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import top.igotcha.eduservice.entity.EduSubject;
import top.igotcha.eduservice.entity.excel.SubjectData;
import top.igotcha.eduservice.service.EduSubjectService;
import top.igotcha.commonutils.exception.GuliException;

/**
 * @author Gotcha
 * @date 2021/8/5
 * @describe
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {
    //因为监听器无法被Spring管理，所以不能进行注入，只能手动new
    //listener filter servlet是平级关系，所以不能被管理
    public EduSubjectService subjectService;

    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null){
            throw new GuliException(20001,"文件数据为空");
        }
        System.out.println(subjectData.getOneSubjectName());
        System.out.println(subjectData.getTwoSubjectName());
        //逐行读取，每次读取两个值，第一个是一级分类，第二个是二级分类
        //判断一级分类是否重复
        EduSubject existOneSubject = existOneSubject(subjectService, subjectData.getOneSubjectName());
        if(existOneSubject == null){
            //不存在该一级分类，则进行添加
            existOneSubject = new EduSubject();
            existOneSubject.setParentId("0");
            existOneSubject.setTitle(subjectData.getOneSubjectName());
            subjectService.save(existOneSubject);
        }
        String parentId = existOneSubject.getId();

        EduSubject existTwoSubject = existTwoSubject(subjectService, subjectData.getTwoSubjectName(), parentId);
        if (existTwoSubject == null){
            existTwoSubject = new EduSubject();
            existTwoSubject.setParentId(parentId);
            existTwoSubject.setTitle(subjectData.getTwoSubjectName());
            subjectService.save(existTwoSubject);
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    //判断一级分类是否可以添加
    private EduSubject existOneSubject(EduSubjectService subjectService,String name){
        EduSubject oneSubject = subjectService.getOne(new QueryWrapper<EduSubject>().eq("title", name).eq("parent_id", "0"));
        return oneSubject;
    }

    //判断二级分类是否可以添加
    private EduSubject existTwoSubject(EduSubjectService subjectService,String name,String parentId){
        EduSubject oneSubject = subjectService.getOne(new QueryWrapper<EduSubject>().eq("title", name).eq("parent_id", parentId));
        return oneSubject;
    }
}
